<template>
  <div class="app-container">
    <el-container>
      <el-aside width="300px" style="max-height:100%;overflow: auto">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            :highlight-current="true"
            @node-click="handleNodeClick"
          />
        </div>
      </el-aside>
      <el-main style="overflow: auto">

        <!--用户数据-->
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" @submit.native.prevent>
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="queryParams.username"
                placeholder="请输入用户名称"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="真实姓名" prop="realname">
              <el-input
                v-model="queryParams.realname"
                placeholder="请输入真实姓名"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button

              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:user:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button

              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >导入
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table
          ref="table"
          v-loading="loading"
          stripe border
          :data="userList"
          @selection-change="handleSelectionChange"
          @row-dblclick="handleUpdate"
          
          @row-contextmenu="(row,column,e)=>utils.rightBtn(row,column,e,this,'table')"
        >
          <el-table-column type="selection" width="60" align="center"/>
          <el-table-column label="序号" width="100" type="index" align="center"/>
          <el-table-column label="用户名" min-width="150" align="center" prop="username"/>
          <el-table-column label="真实姓名" min-width="150" align="center" prop="realname"/>
          <el-table-column label="用户状态" align="center">
            <template slot-scope="scope">
              <span class="label label-danger" v-if="scope.row.status=='S'">停用</span>
              <span v-else-if="scope.row.status=='N'">正常</span>
            </template>
          </el-table-column>
          <el-table-column label="所属机构" min-width="150" align="center" prop="dept.name"/>
          <el-table-column label="所属角色" min-width="200" align="center" prop="rolecodes"/>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-main>
    </el-container>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" :modal="false" :appendToBody="false" width="800px" :top="scrollTop"
               v-dialog-drag :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="11" :offset="1">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" :disabled="disabled" placeholder="请输入用户名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="form.password" :disabled="disabled" show-password
                        auto-complete="new-password"
                        placeholder="请输入用户密码" type="password"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="11" :offset="1">
            <el-form-item label="真实姓名" prop="realname">
              <el-input v-model="form.realname" placeholder="请输入真实姓名"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11" :offset="1">
            <template>
              <el-form-item label="机构操作员" prop="type">
                <el-radio v-model="form.type" label="Y">是</el-radio>
                <el-radio v-model="form.type" label="N">否</el-radio>
              </el-form-item>
            </template>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="所属机构" prop="branchcodeName">
              <el-input v-model="form.branchcodeName" placeholder="请选择领料部门" @click.native="openOrganization()"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11" :offset="1">
            <template>
              <el-form-item label="用户状态" prop="status">
                <el-select v-model="form.status" placeholder="选择状态" size="small">
                  <el-option value="N" key="N" label="正常"></el-option>
                  <el-option value="S" key="S" label="停用"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="电子邮件" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11" :offset="1">
            <template>
              <el-form-item label="是否点检下载账号" prop="prop6">
                <el-radio v-model="form.prop6" label="Y">是</el-radio>
                <el-radio v-model="form.prop6" label="N">否</el-radio>
              </el-form-item>
            </template>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入联系电话" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
                        maxlength="11"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11" :offset="1">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="form.mobile" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
                        placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23" :offset="1">
            <el-form-item label="备注">
              <el-input v-model="form.memo" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="角色权限">
          <el-tree
            class="tree-border"
            :data="roleOptions"
            show-checkbox
            default-expand-all
            ref="roleTree"
            node-key="id"
            :check-strictly="!form.deptCheckStrictly"
            :default-checked-keys="checkedKeys"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <div v-show="exportMenu">
      <ul id="exportMenu" class="exportMenu">
        <li class="exportMenu__item" @click="()=>utils.exportFiles('1',this,'table')"><i
          class="el-icon-document-remove"></i>导出选中项成XLSX
        </li>
        <li class="exportMenu__item" @click="()=>utils.exportFiles('2',this,'table')"><i class="el-icon-document"></i>导出本页成XLSX
        </li>
        <li class="exportMenu__item" @click="()=>utils.exportFiles('3',this,'table')"><i
          class="el-icon-document-copy"></i>导出所有项成XLSX
        </li>
      </ul>
    </div>
    <el-dialog title="选择要导出的列" :visible.sync="exportFile" :modal="false" :appendToBody="false" v-dialog-drag
               width="600px" :top="scrollTop" @close="()=>utils.closeExportFile(this)">
      <el-row>
        <el-col ::offset="1" :span="5" style="margin-bottom: 10px">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                       @change="(val)=>utils.handleCheckAllChange(val,this,codeAll)">全选
          </el-checkbox>
        </el-col>
      </el-row>
      <el-checkbox-group v-model="queryParams.exportColumnName"
                         @change="(val)=>utils.handleCheckedCitiesChange(val,this,codeAll)">
        <el-row>
          <el-col ::offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="username">用户名</el-checkbox>
          </el-col>
          <el-col ::offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="realname">真实姓名</el-checkbox>
          </el-col>
          <el-col ::offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="status">用户状态</el-checkbox>
          </el-col>
          <el-col ::offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="name">所属机构</el-checkbox>
          </el-col>
          <el-col ::offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="rolenames">所属角色</el-checkbox>
          </el-col>
        </el-row>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleExport">保 存</el-button>
        <el-button @click="exportFile = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="打印预览" :visible.sync="prints" :modal="false" :appendToBody="false" v-dialog-drag
               width="400px" :top="scrollTop">
      <div id="printId">
        <template v-for="(item,index) of printsList">
          <div :key="index" style="width: 240px;height: 240px;border: 1px #999 solid;margin: auto">
            <div style="width: 200px;height: 200px;margin: auto"><img :src="'http://192.168.0.31:8007/' +item.qrcode"
                                                                      alt="二维码" style="width: 100%;height: 100%"></div>
            <div style="text-align: center;">{{item.realname}}</div>
          </div>
          <div :key="index" v-if="index%4 == 3" style="page-break-after: always;"></div>
        </template>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePrints">保 存</el-button>
        <el-button @click="prints = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--    组织机构-->
    <organization :visibles="organization" :branchcode="form.branchinnercode"
                  @closeDialog="closeOrganization"></organization>

    <!--   导入-->
    <FileImport :importData="importData"></FileImport>
  </div>
</template>

<script>
  import {
    listUser,
    getAddInfo,
    getUser,
    delUser,
    addUser,
    updateUser,
    getUserNames,
    exportUser,
    resetUserPwd,
    changeUserStatus,
    importTemplate
  } from "@/api/system/user";
  import {getToken} from "@/utils/auth";
  import {print} from '@/utils/print'
  import {treeselect} from "@/api/system/dept";
  import {roleTreeselect} from "@/api/system/role";


  export default {
    name: "User",
    components: {},
    data() {
      return {
        checkedKeys: [],
        disabled: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户表格数据
        userList: null,
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        //组织机构弹框
        organization: false,
        // 部门名称
        deptName: undefined,
        // 默认密码
        initPassword: undefined,
        // 日期范围
        dateRange: [],
        // 状态数据字典
        statusOptions: [],
        // 性别状态字典
        sexOptions: [],
        // 岗位选项
        postOptions: [],
        // 角色选项
        roleOptions: [],
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          username: null,
          realname: null,
          branchinnercode: null,
          exprotDataSize: null,
          exportColumnName: [],
          subCloumn: null,
          exportCheckData: [],
        },
        // 表单校验
        rules: {
          username: [
            {required: true, message: "用户名称不能为空", trigger: "blur"}
          ],
          realname: [
            {required: true, message: "真实姓名不能为空", trigger: "blur"}
          ],
          password: [
            {required: true, message: "用户密码不能为空", trigger: "blur"}
          ],
          email: [
            {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"]
            }
          ],
          mobile: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: ["blur", "change"]
            }
          ],
          tel: [
            {
              pattern: /^(0[1-9]{2})-\d{8}$|^(0[1-9]{3}-(\d{7,8}))$/g,
              message: "请输入正确的电话号码",
              trigger: ["blur", "change"]
            }
          ]
        },
        scrollTop: null,
        exportMenu: false,
        exportFile: false,
        checkAll: false,
        isIndeterminate: false,
        codeAll: ["username", "realname", "status", "name", "rolenames"],
        importData: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          //上传的地址
          url: "/system/user/getSheetName",
          //导入地址
          importUrl: "/system/user/importData",
          //文件导入后获取详细数据接口
          importParamUrl: '/system/user/importParam',
          //下载模板方法
          import: importTemplate,
          codeList: []
        },
        //打印
        prints: false,
        printsList: []
      };
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val);
      },
    },
    created() {
      this.getTreeselect();
    },
    methods: {
      /** 查询用户列表 */
      getList() {
        this.loading = true;
        listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
            this.userList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        var that = this;
        treeselect().then(response => {
          console.log(response.data)
          this.deptOptions = response.data;
          //排序
          this.deptOptions.sort(this.compare("id"))
          this.$nextTick(() => {
            // treeBox 元素的ref   value 绑定的node-key
            this.$refs.tree.setCurrentKey(this.selectChildren(response.data[0]));
            this.queryParams.branchinnercode = this.selectChildren(response.data[0]);
            this.getList();
          });
        });

      },
      //排序方法
      compare(propertyName) {
        return function (object1, object2) {
          var value1 = object1[propertyName];
          var value2 = object2[propertyName];
          if (value2 < value1) {
            return 1;
          } else if (value2 > value1) {
            return -1;
          } else {
            return 0;
          }
        }
      },
      //获取树结构第一条数据
      selectChildren(data) {
        if (data.children != undefined) {
          return this.selectChildren(data.children[0]);
        } else {
          var ids = data.id;
          return ids;
        }
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.branchinnercode = data.id;
        this.getList();
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },

      // 表单重置
      reset() {
        this.checkedKeys = [];
        this.form = {
          branchinnercode: undefined,
          username: undefined,
          realname: undefined,
          password: null,
          type: 'Y',
          status: 'N',
          prop6: 'N',
          tel: undefined,
          email: undefined,
          mobile: undefined,
          memo: undefined,
          roles: []
        };
        this.resetForm("form");
      },
      //打开组织机构弹框
      openOrganization() {
        this.organization = true;
      },
      //关闭组织机构弹框触发的方法
      closeOrganization(list) {
        if (list != undefined && list != [] && list != null) {
          this.form.branchinnercode = list[0].id;
          this.form.branchcodeName = list[0].name;
          this.$refs.form.clearValidate(['branchcodeName'])
        }
        this.organization = false;
      },
      /** 根据同户名查询角色树结构 */
      getRoleTreeselect(username) {
        return roleTreeselect(username).then(response => {
          this.roleOptions = response.roles;
          this.checkedKeys = response.checkedKeys;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.username);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        var branchinnercode = this.queryParams.branchinnercode;
        getAddInfo(branchinnercode).then(response => {
          this.roleOptions = response.roles;
          this.open = true;
          this.title = "添加用户";
          this.form.password = this.initPassword;
          this.form.branchinnercode = response.dept.branchinnercode;
          this.form.branchcodeName = response.dept.name;
          this.disabled = false;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const username = row.username || this.ids.join();
        this.getRoleTreeselect(username);
        getUser(username).then(response => {
          var l = response.data;
          this.form = l;
          this.form.branchinnercode = l.dept.branchinnercode;
          this.form.branchcodeName = l.dept.name;
          this.open = true;
          this.title = "查看用户";
          this.form.password = "*******";
          this.disabled = true;
        });
      },
      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        this.$prompt('请输入"' + row.username + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then(({value}) => {
          resetUserPwd(row.username, value).then(response => {
            this.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            var roles = this.$refs.roleTree.getCheckedKeys();
            this.form.roles = roles;
            if (this.form.userId) {
              updateUser(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.form.password = '';
                this.getList();
              });
            } else {
              addUser(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const usernames = row.username || this.ids;
        this.$confirm('是否确认删除用户编号为"' + usernames + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delUser(usernames);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导入按钮操作 */
      handleImport() {
        this.importData.codeList = [{code: 'username', name: '用户名'},
          {code: 'realname', name: '真实姓名'},
          {code: 'type', name: '机构操作员'},
          {code: 'branchinnercode', name: '所属机构'},
          {code: 'status', name: '是否停用'},
          {code: 'email', name: '电子邮件'},
          {code: 'prop6', name: '是否点检下载账号'},
          {code: 'tel', name: '联系电话'},
          {code: 'mobile', name: '手机号码'},
          {code: 'memo', name: '备注'}]
        this.importData.title = "用户导入";
        this.importData.open = true;
      },


      /** 导出按钮操作 */
      handleExport() {
        this.utils.handleExport(this, 'table', this.userList, 'codetype', exportUser);
      },
      //打开打印窗口
      openPrints() {
        getUserNames(this.ids).then(res => {
          this.printsList = res.rows
          this.prints = true
        })

      },
      //打印确认
      handlePrints() {
        print(document.getElementById('printId').innerHTML);
      },
    },
    mounted() {
      // 阻止默认行为
      document.body.ondrop = function (event) {
        event.preventDefault();
        event.stopPropagation();
      };
      this.utils.columnDrop(this, 'table', 'displayMeta')
      this.utils.mounteds(this);
    },
    destroyed() {
      this.utils.destroyeds(this);
    }
  };
</script>

<style type="text/css" scoped>
    .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content{
      color: rgb(249, 156, 52);
    }
</style>
